
//The MIT License (MIT)
//
//Copyright (c) 2013 Rafał Augustyniak
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#import "RAViewController.h"
#import "RATreeView.h"
#import "RADataObject.h"
#import "AppDelegate.h"
#import "JXChatViewController.h"
#import "CoreDataEntity.h"
#import "ChatViewController.h"
#import "EMSearchBar.h"
#import "EMSearchDisplayController.h"
#import "RealtimeSearchUtil.h"
#import "ChatListCell.h"
#import "MyEMBuddy.h"

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface RAViewController () <RATreeViewDelegate, RATreeViewDataSource,UISearchBarDelegate, UISearchDisplayDelegate>

@property (strong, nonatomic) NSArray *data;
@property (strong, nonatomic) id expanded;
@property (weak, nonatomic)   RATreeView *treeView;

@property (strong, nonatomic) EMSearchBar *searchBar;
@property (strong, nonatomic) EMSearchDisplayController *searchController;
@end

@implementation RAViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withArray:(NSArray*)array
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.data = [NSArray arrayWithArray:array];
    }
    return self;
}

- (id)initWithArray:(NSArray*)array
{
    self = [super init];
    if (self) {
        self.data = [NSArray arrayWithArray:array];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    RATreeView *treeView = [[RATreeView alloc] initWithFrame:CGRectMake(0, -35, self.view.frame.size.width, self.view.frame.size.height) style:RATreeViewStyleGrouped];
    treeView.delegate = self;
    treeView.dataSource = self;
    treeView.separatorStyle = RATreeViewCellSeparatorStyleSingleLine;
//    treeView.treeHeaderView = self.searchBar;
    
    [treeView reloadData];
    //  [treeView expandRowForItem:phone withRowAnimation:RATreeViewRowAnimationLeft]; //expands Row
    [treeView setBackgroundColor:UIColorFromRGB(0xFFFFFF)];
    
    self.treeView = treeView;
    
    //  [self.treeView setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:treeView];
    [self searchController];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
        self.treeView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        //    CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
        //    float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;
        self.treeView.contentInset = UIEdgeInsetsMake(0, 0.0, 0.0, 0.0);
        self.treeView.contentOffset = CGPointMake(0.0, -0);
    }
    
    self.treeView.frame = self.view.bounds;
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    _searchBar.text = @"";
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
    [_searchBar resignFirstResponder];
    [_searchBar setShowsCancelButton:NO animated:YES];
}

- (UISearchBar *)searchBar
{
    if (_searchBar == nil) {
        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 44)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索联系人";
        _searchBar.backgroundColor = [UIColor colorWithRed:0.747 green:0.756 blue:0.751 alpha:1.000];
    }
    
    return _searchBar;
}

- (EMSearchDisplayController *)searchController
{
    if (_searchController == nil) {
        _searchController = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _searchController.delegate = self;
        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        __weak RAViewController *weakSelf = self;
        
        [_searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            static NSString * CellIdentifier = @"Cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            EMBuddy * buddy = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            cell.textLabel.text = [CoreDataEntity selectUserNameWithUserId:buddy.username];
            cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
            cell.imageView.image = [UIImage imageNamed:@"chatListCellHead.png"];
            if (indexPath.row % 2 == 1) {
                cell.contentView.backgroundColor = RGBACOLOR(246, 246, 246, 1);
            }else{
                cell.contentView.backgroundColor = [UIColor whiteColor];
            }
            
            return cell;
        }];
        
        [_searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 50.0f;
        }];
        
        [_searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            [weakSelf.searchController.searchBar endEditing:YES];
            
            EMBuddy * buddy = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:buddy.username isGroup:NO];
            chatVC.title = buddy.username;
            [weakSelf.leveyTabBarController.navigationController pushViewController:chatVC animated:YES];
        }];
    }
    
    return _searchController;
}


#pragma mark TreeView Delegate methods
- (CGFloat)treeView:(RATreeView *)treeView heightForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 40;
}

- (NSInteger)treeView:(RATreeView *)treeView indentationLevelForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 3 * treeNodeInfo.treeDepthLevel;
}

- (BOOL)treeView:(RATreeView *)treeView shouldExpandItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return YES;
}

- (BOOL)treeView:(RATreeView *)treeView shouldItemBeExpandedAfterDataReload:(id)item treeDepthLevel:(NSInteger)treeDepthLevel
{
    if ([item isEqual:self.expanded]) {
        return YES;
    }
    
    return NO;
}
- (void)treeView:(RATreeView *)treeView willDisplayCell:(UITableViewCell *)cell forItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    
    //  if (treeNodeInfo.treeDepthLevel == 0) {
    //    cell.backgroundColor = UIColorFromRGB(0xFFFFFF);
    ////      cell.imageView.image = xl;
    ////      [cell addSubview:imgView];
    //  } else if (treeNodeInfo.treeDepthLevel == 1) {
    //    cell.backgroundColor = UIColorFromRGB(0xFFFFFF);
    ////      cell.imageView.image = xl;
    ////      [cell addSubview:imgView];
    //  } else if (treeNodeInfo.treeDepthLevel == 2) {
    //    cell.backgroundColor = UIColorFromRGB(0xFFFFFF);
    //  }
}

#pragma mark TreeView Data Source
-(UITableViewCell *)treeView:(RATreeView *)treeView cellForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    //  NSInteger numberOfChildren = [treeNodeInfo.children count];
    RAcell *cell = [[RAcell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    
    //    RAcell *cell = [treeView dequeueReusableCellWithIdentifier:@"cell"];
    //    if (cell == nil) {
    //        cell = [[RAcell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    //    }
    
    //  cell.detailTextLabel.text = [NSString stringWithFormat:@"Number of children %@", [@(numberOfChildren) stringValue]];
    //    UIImage *xl = [UIImage imageNamed:@"xiala1"];
    //    UIImageView *imgView = [[UIImageView alloc] initWithImage:xl];
    
    if (treeNodeInfo.treeDepthLevel == 0) {
        [cell showOneImg];
        cell.backgroundColor = UIColorFromRGB(0xFFFFFF);
        //        imgView.frame = CGRectMake(10, 10, 20, 20);
        //        [cell addSubview:imgView];
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(40, 0, self.view.frame.size.width-40, 40)];
        lb.text = ((RADataObject *)item).name;
        lb.font = [UIFont boldSystemFontOfSize:16];
        lb.numberOfLines = 0;
        lb.adjustsFontSizeToFitWidth = YES;
        [cell addSubview:lb];
        
    } else if (treeNodeInfo.treeDepthLevel == 1) {
        cell.backgroundColor = UIColorFromRGB(0xFFFFFF);
        //        imgView.frame = CGRectMake(20, 10, 20, 20);
        //        [cell addSubview:imgView];
        [cell showTwoImg];
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, self.view.frame.size.width-25, 40)];
        lb.text = ((RADataObject *)item).name;
        lb.font = [UIFont boldSystemFontOfSize:16];
        [cell addSubview:lb];
    } else if (treeNodeInfo.treeDepthLevel == 2) {
        cell.backgroundColor = UIColorFromRGB(0xFFFFFF);
        
        //        UIImage *tx = [UIImage imageNamed:@"persontx"];
        UIImage *tx;
        
        /*暂时不用*/
        /*
         NSString* headUrl = ((RADataObject *)item).headUrl;
         if (headUrl.length>0) {
         NSString * headPath = [NSString stringWithFormat:@"http://115.28.239.113:8080%@",headUrl];
         NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:headPath]];
         tx = [UIImage  imageWithData:data];
         NSLog(@"headPath = %@",headPath);
         }else{
         tx = [UIImage imageNamed:@"persontx"];
         }
         */
        tx = [UIImage imageNamed:@"persontx"];
        /******/
        //        UIImage * tx = [UIImage  imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:((RADataObject *)item).headUrl]]];
        UIImageView *tximgView = [[UIImageView alloc] initWithImage:tx];
        tximgView.frame = CGRectMake(30, 5, 30, 30);
        [cell addSubview:tximgView];
        
        
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(70, 0, self.view.frame.size.width-25, 40)];
        lb.text = ((RADataObject *)item).name;
        lb.font = [UIFont boldSystemFontOfSize:16];
        [cell addSubview:lb];
    }
    return cell;
}

- (void)treeView:(RATreeView *)treeView willExpandRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo{
    RAcell *cell = (RAcell *)[treeView cellForItem:item];
    cell.delegate = self;
    if (treeNodeInfo.treeDepthLevel == 0) {
        [cell tapDown];
    }else if(treeNodeInfo.treeDepthLevel == 1){
        [cell tapDown2];
    }
    
}

-(void)treeView:(RATreeView *)treeView willCollapseRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo{
    RAcell *cell = (RAcell *)[treeView cellForItem:item];
    cell.delegate = self;
    
    if (treeNodeInfo.treeDepthLevel == 0) {
        //        [cell tapUp];
        [cell tapUp];
    }else if(treeNodeInfo.treeDepthLevel == 1){
        //        [cell tapUp2];
        [cell tapUp2];
    }
}

- (void)treeView:(RATreeView *)treeView didSelectRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo;
{
    [treeView deselectRowForItem:item animated:YES];
    RADataObject *data = item;

    if (treeNodeInfo.treeDepthLevel == 2) {
        UserInfoEntity * user = [CoreDataEntity getUserByUserId:data.userId];
        if ([[constant getUserId] isEqualToString:user.userID]) {
            TTAlertNoTitle(@"亲,不能和自己聊天的.");
            return;
        }
        ChatViewController * sendView = [[ChatViewController alloc] initWithChatter:user.userID isGroup:NO];
        [self.leveyTabBarController.navigationController pushViewController:sendView  animated:true];
    }
}

- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item
{
    
    if (item == nil) {
        return [self.data count];
    }
    
    RADataObject *data = item;
    return [data.children count];
}

- (id)treeView:(RATreeView *)treeView child:(NSInteger)index ofItem:(id)item
{
    RADataObject *data = item;
    if (item == nil) {
        return [self.data objectAtIndex:index];
    }
    
    return [data.children objectAtIndex:index];
}

#pragma mark -
#pragma mark UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    CommunicationViewController * com = (CommunicationViewController *)[constant findViewController:self.view.superview.superview];
    com.topBarContainer.enabled = NO;
    
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSMutableArray * searchDataSource = [NSMutableArray array];
    NSArray * dataSource = [CoreDataEntity selectAllUserInfo];
    
    for (EMBuddy * buddy in dataSource) {
        NSString * realName = [CoreDataEntity selectUserNameWithUserId:buddy.username];
        MyEMBuddy * myBuudy = [[MyEMBuddy alloc] initWithRealName:realName buddy:buddy];
        [searchDataSource addObject:myBuudy];
    }
    
    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:searchDataSource searchText:(NSString *)searchText collationStringSelector:@selector(realName) resultBlock:^(NSArray *results) {
        if (results) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [searchDataSource removeAllObjects];
                for (MyEMBuddy * myBuddy in results) {
                    EMBuddy * buddy = myBuddy.buddy;
                    [searchDataSource addObject:buddy];
                }
                [self.searchController.resultsSource removeAllObjects];
                [self.searchController.resultsSource addObjectsFromArray:searchDataSource];
                [self.searchController.searchResultsTableView reloadData];
            });
        }
    }];
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    CommunicationViewController * com = (CommunicationViewController *)[constant findViewController:self.view.superview.superview];
    com.topBarContainer.enabled = YES;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

@end
